package com.kaifamiao.wendao.controller;

import com.alibaba.fastjson2.JSONObject;
import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Explain;
import com.kaifamiao.wendao.entity.Level;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.exception.ServiceException;
import com.kaifamiao.wendao.service.ExplainService;
import com.kaifamiao.wendao.service.LevelService;
import com.kaifamiao.wendao.service.TopicService;
import com.kaifamiao.wendao.utils.Constants;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.tinylog.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/explain/*")
public class ExplainServlet extends HttpServlet {

    private ExplainService service=new ExplainService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=UTF-8");
        super.service(req, resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out= resp.getWriter();
        String id=req.getParameter("id");
        String tid=req.getParameter("tid");
        if(com.mysql.cj.util.StringUtils.isNullOrEmpty(id) || StringUtils.isEmptyOrWhitespaceOnly(id)){
            List<Explain> list=service.findAll(Long.valueOf(tid));
            String json= JSONObject.toJSONString(Map.of("explains",list));
            out.println(json);
            return;
        }

        Long i = Long.valueOf(id);
        Explain e = service.find(Long.valueOf(tid));
        String json = JSONObject.toJSONString(Map.of( "explains", e == null ? "" : e ));
        out.println( json );
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        Map<String,Object> map = new HashMap<>();

        Explain e = new Explain();
        String cont = req.getParameter( "content" );
        e.setContent(cont);
        String addr = req.getParameter( "publishAddress" );
        e.setPublishAddress(addr);
        String text = req.getParameter( "publishTime" );
        try {
            LocalDateTime putime = LocalDateTime.parse(text);
            e.setPublishTime(putime);
        } catch (Exception exception) {
            map.put("success", false);
            map.put("message", "发布时间格式错误");
            out.println( JSONObject.toJSONString( map ) );
            return;
        }

        try {
            boolean res = service.save(e);
            if( res ) {
                map.put("success", true);
                map.put("message", "保存成功");
            } else {
                map.put( "success", false );
                map.put( "message", "保存失败" );
            }
        }
        // 捕获在Service中显式抛出的异常
        catch (ServiceException ex) {
            Logger.error( ex, "评论信息保存失败" );
            map.put( "success", false );
            map.put( "message", "保存失败" );
            map.put( "cause", ex.getMessage() );
        }
        // 捕获除ServiceException之外的其它异常
        catch (Exception ex) {
            Logger.error( ex, "评论信息保存失败" );
            map.put( "success", false );
            map.put( "message", "保存失败" );
            map.put( "cause", ex.getMessage() );
        }

        out.println( JSONObject.toJSONString( map ) );
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out=resp.getWriter();
        Map<String,Object> map=new HashMap<>();
        Explain e=new Explain();
        try {
            BeanUtils.populate(e, req.getParameterMap());
        } catch (Exception ex) {
            Logger.error(ex, "数据封装失败");
            map.put("success", false);
            map.put("message", "出错了");
            out.println( JSONObject.toJSONString( map ) );
            return;
        }
        String text = req.getParameter( "publishTime" );
        try {
            LocalDateTime putime = LocalDateTime.parse(text);
            e.setPublishTime(putime);
        } catch (Exception exception) {
            map.put("success", false);
            map.put("message", "发布时间格式错误");
            out.println( JSONObject.toJSONString( map ) );
            return;
        }
        try {
            boolean res = service.update(e);
            map.put("success", res);
            map.put("message", res ? "修改成功" : "修改失败" );
        } catch (Exception ex) {
            Logger.error(ex, "修改失败");
            map.put("success", false);
            map.put("message", "修改失败");
            map.put("cause", ex.getMessage());
        }

        out.println( JSONObject.toJSONString( map ) );

    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        Map<String,Object> map = new HashMap<>();

        String sid = req.getParameter( "id" );
        if( StringUtils.isNullOrEmpty(sid) || StringUtils.isEmptyOrWhitespaceOnly(sid) ){
            map.put("success", false);
            map.put("message", "被删除评论编号不能为空");
            out.println( JSONObject.toJSONString( map ) );
            return;
        }

        Long id = null;
        try {
            id = Long.valueOf(sid);
        } catch (Exception e ) {
            Logger.error(e, "评论编号必须是整数形式");
            map.put("success", false);
            map.put("message", "评论编号必须是整数形式");
            out.println( JSONObject.toJSONString( map ) );
            return;
        }

        try {
            boolean res = service.remove(id);
            if(res) {
                map.put("success", true);
                map.put("message", "删除成功");
            } else {
                map.put("success", false);
                map.put("message", "删除失败");
            }
        } catch (Exception e) {
            Logger.error(e, "评论信息删除失败");
            map.put("success", false);
            map.put("message", "删除失败");
            map.put("cause", e.getMessage());
        }

        out.println( JSONObject.toJSONString( map ) );
    }


}
